

/**定时触发组件 */
export class ScheduleCom {
    funcs: { cb: ()=>void, interval: number, count: number, nowTime: number ,isPause:boolean}[] = [];
    private isCreal: boolean = false;

    update(dt: number): void {
        if (this.isCreal) {
            this.funcs = [];
            this.isCreal = false;
            return;
        }
        if (this.funcs.length == 0) return;
        let temp = []
        for (let i = 0; i < this.funcs.length; i++) {
            let element = this.funcs[i];
            if(element.isPause){
                temp.push(element);
                continue;
            }
            if (element.nowTime <= 0) {
                element.cb();
                if (element.count <= -1) {
                    element.nowTime = element.interval
                    temp.push(element);
                    continue;
                }
                element.count--;
                if (element.count > 0) {
                    element.nowTime = element.interval
                    temp.push(element);
                }
            } else {
                temp.push(element);
            }
            element.nowTime -= dt;
        }
        this.funcs = temp
    }

    add(cb: ()=>void, interval: number, count?: number) {
        let temp = {
            cb,
            interval,
            nowTime: interval,
            count: (count) ? count : -1,
            isPause:false
        }
        this.funcs.push(temp)

        return temp
    }

    clearAll() {
        this.funcs = [];
        this.isCreal = true;
    }
}

